package com.hmall.order.task;

import com.hmall.clients.ItemClient;
import com.hmall.order.mapper.OrderDetailMapper;
import com.hmall.order.mapper.OrderMapper;
import com.hmall.order.pojo.Order;
import com.hmall.order.pojo.OrderDetail;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @Description OrderTask
 * @Author dmx
 * @Date 2024-11-16
 */
@Component
@Slf4j
public class OrderTask {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private ItemClient itemClient;
    @Scheduled(cron = "0 */1 * * * ?")//定时任务每隔一分钟执行一次
    public void updateOrderStatus(){
        // 当前时间
        LocalDateTime now = LocalDateTime.now();
        // 计算30分钟前的时间
        LocalDateTime thirtyMinutesAgo = now.minusMinutes(30);

        // 查询status为1（未支付），并且下单时间超过30分钟的订单
        List<Order> unpaidOrders = orderMapper.selectUnpaidOrders(Timestamp.valueOf(thirtyMinutesAgo));

        for (Order order : unpaidOrders) {
            // 调用item-service，根据商品id、商品数量恢复库存
            OrderDetail orderDetail=orderDetailMapper.selectByOrderId(order.getId());
            //查询购买的数量
            Integer num = orderDetail.getNum();
            itemClient.updateStock(orderDetail.getItemId(), -num);

            // 根据orderId修改订单status为5（交易取消，订单关闭）
            order.setStatus(5); // 5 表示交易取消，订单关闭
            order.setUpdateTime(Timestamp.valueOf(LocalDateTime.now())); // 设置更新时间为当前时间
            orderMapper.updateById(order);

        }
    }
}
